package com.maple.common.utils;

import android.hardware.usb.UsbDevice;
import android.os.Message;
import android.text.TextUtils;

import com.maple.utils.util.LogUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

public class Tools {


    // 将16进制字符串转化为字节数组
    public static byte[] hexStr2Bytes(String paramString) {
        int i = paramString.length() / 2;

        byte[] arrayOfByte = new byte[i];
        int j = 0;
        while (true) {
            if (j >= i)
                return arrayOfByte;
            int k = 1 + j * 2;
            int l = k + 1;
            arrayOfByte[j] = (byte) (0xFF & Integer.decode(
                    "0x" + paramString.substring(j * 2, k)
                            + paramString.substring(k, l)).intValue());
            ++j;
        }
    }

    public static boolean isDealMqtt(String readMessage) {
        return readMessage != null && readMessage.length() > 7 && (('8' == readMessage.charAt(6)) && ('2' == readMessage.charAt(7)));
    }

    // 将字节数组转化为16进制字符串，确定长度
    public static String bytesToHexString(byte[] bytes, int a) {
        String result = "";
        for (int i = 0; i < a; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);// 将高24位置0
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }

    // 将字节数组转化为16进制字符串，不确定长度
    public static String Bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);// 将高24位置0
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }

    //将16进制字符串转字节
    public static byte[] hexString2Bytes(String hex) {
        if ((hex == null) || (hex.equals(""))) {
            return null;
        } else if (hex.length() % 2 != 0) {
            return null;
        } else {
            hex = hex.toUpperCase();
            int len = hex.length() / 2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i = 0; i < len; i++) {
                int p = 2 * i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p + 1]));
            }
            return b;
        }
    }

    //字符转字节
    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    //将16进制字符串转字符串
    public static String hex2String(String hex) {
        String r = bytes2String(hexString2Bytes(hex));
        return r;
    }

    //将字节转字符串
    public static String bytes2String(byte[] b) {
        try {
            String r = new String(b,"UTF-8");
            return r;
        }catch (UnsupportedEncodingException e) {
        }
        return "";
    }

    public static String getDealMqttDeviceNum(String readMessage) {
        String deviceNum = "";
        if (('8' == readMessage.charAt(7)) && ('2' == readMessage.charAt(8)) && ('0' == readMessage.charAt(9)) && ('8' == readMessage.charAt(10))) {
            String newMessage = readMessage.substring(11);
            if (newMessage.indexOf("00") > 0) {
                if (newMessage.indexOf("00") % 2 == 0) {
                    deviceNum = Tools.hex2String(newMessage.substring(0, newMessage.indexOf("00")));
                } else {
                    deviceNum = Tools.hex2String(newMessage.substring(0, newMessage.indexOf("00") + 1));
                }

            } else {
                deviceNum = Tools.hex2String(newMessage.substring(0, newMessage.length() - 4));
            }
        }
        return deviceNum;
    }

    public static String dealMqtt(String readMessage) {
        try {
            String newMessage = readMessage.substring(11);
            //取小数点
            String substring = newMessage.substring(0, 2);
            byte[] bytesPoint = Tools.hexString2Bytes(substring);
            int point = bytesPoint[0] & 0xC0;
            point = point >> 6;
//            String pWeight = newMessage.substring(8, 16); //皮重
            String jWeight = newMessage.substring(16, 24);//净重
//            String mWeight = newMessage.substring(24, 32); //毛重

            byte[] bytes = hexString2Bytes(jWeight);

            int sum = 0;
            for (int i = 0; i < bytes.length; i++) {
                int copy = bytes[i] & 0xFF;
                sum += copy << (8 * i);
            }

            String weight = String.valueOf(sum);
            return setWeightMqtt(getSmallWeight(weight, point));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String setWeightMqtt(String weight) {
        if (!TextUtils.isEmpty(weight) && (weight.indexOf('.') == 0 || weight.contains("-."))) {
            weight = weight.replace(".", "0.");
        }
        return weight;
    }

    public static String getSmallWeight(String value, int point) {
        if (point == 0) {
            return value;
        }

        if (TextUtils.isEmpty(value)) {
            return "";
        }

        if (value.length() > point) {
            return value.substring(0, value.length() - point) + "." + value.substring(value.length() - point);
        } else {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < point - value.length(); i++) {
                sb.append("0");
            }

            if (sb.length() == 0) {
                return "0." + value;
            } else {
                return "0." + sb.toString() + value;
            }
        }

    }

    public static String dealWeightOld(byte[] buffer, int num) {
        try {
            byte[] buffer_new = new byte[1024];
            int n = 0;
            for (int i = 0; i < num; i++) {
                if ((buffer[i] == 0x0d) && (buffer[i + 1] == 0x0a)) {
                    buffer_new[n] = 0x0a;
                    i++;
                } else {
                    buffer_new[n] = buffer[i];
                }
                n++;
            }
            String s = new String(buffer_new, 0, n);
            LogUtils.logGGQ("sssss:" + s);
            return setWeight(s);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    private static String setWeight(String weightCome) {
        if (!TextUtils.isEmpty(weightCome) && weightCome.contains("=")) {
            String weight = parseWeight(weightCome);
            if (weight != null && (weight.indexOf('.') == 0 || weight.contains("-."))) {
                weight = weight.replace(".", "0.");
            }
            return weight;
        }
        return "";
    }

    private static String parseWeight(String weightCome) {
        String[] weights = weightCome.split("=");
        String weight = weights[weights.length - 1].trim();
        StringBuffer sb = new StringBuffer(weight);
        String weightFinal = sb.reverse().toString();
        BigDecimal decimal = new BigDecimal(weightFinal);
        return decimal.stripTrailingZeros().toString();
    }

    /**
     *  异或校验
     *
     * @param data 十六进制串
     * @return checkData  十六进制串
     *
     * */
    public static String checkXor(String data) {
        int checkData = 0;
        for (int i = 0; i < data.length(); i = i + 2) {
            //将十六进制字符串转成十进制
            int start = Integer.parseInt(data.substring(i, i + 2), 16);
            //进行异或运算
            checkData = start ^ checkData;
        }
        return integerToHexString(checkData);
    }

    /**
     * 将十进制整数转为十六进制数，并补位
     */
    public static String integerToHexString(int s) {
        String ss = Integer.toHexString(s);
        if (ss.length() % 2 != 0) {
            ss = "0" + ss;//0F格式
        }
        return ss.toUpperCase();
    }

    /**
     * 累加和校验，并取反
     */
    public static String makeCheckSum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }

        //用256求余最大是255，即16进制的FF
        int mod = total % 256;
        if (mod == 0) {
            return "FF";
        } else {
            String hex = Integer.toHexString(mod).toUpperCase();
            //十六进制数取反结果
            hex = parseHex2Opposite(hex);
            return hex;
        }
    }

    /**
     * 取反
     */
    public static String parseHex2Opposite(String str) {
        String hex;
        //十六进制转成二进制
        byte[] er = parseHexStr2Byte(str);

        //取反
        byte erBefore[] = new byte[er.length];
        for (int i = 0; i < er.length; i++) {
            erBefore[i] = (byte) ~er[i];
        }

        //二进制转成十六进制
        hex = parseByte2HexStr(erBefore);

        // 如果不够校验位的长度，补0,这里用的是两位校验
        hex = (hex.length() < 2 ? "0" + hex : hex);

        return hex;
    }


    /**
     * 将十六进制转换为二进制
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成十六进制
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

}
